<template>
  <div>
    <div class="node" v-has="{action: 'coupon:list', effect: 'move'}">
    <div class="search_box topSelect">
      
      <div class="searchBox1" style="margin-left: 20px">
        <el-button size="small" plain type="primary" icon="el-icon-search" @click="getQueryData">查询</el-button>     
      </div>
    </div>
    <Panel title="优惠券" :intro="intro">
      <div slot='ext' class="examine">
        <el-button v-has="{action: 'coupon:add', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>editStore()">新增</el-button>
    </div>
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
    >
    <template slot="operation" slot-scope="operation">
          <el-button size="mini" type="primary" icon="el-icon-success"
            v-has="{action: 'client:coupon:confirm', effect: 'move'}"
            v-if="operation.row.state==1"
            @click="()=>checkCoupon(operation.row.id)"
          >审核通过</el-button>
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
          layout="sizes, prev, pager, next"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    <!-- 添加编辑 start-->
    <ModalPanel 
      :visible='visible'
      title="添加/编辑"
      :showFooter='showUpdate'
      :onCancel="onCancel"
      class="bannerDialog"
      :onOk="onSubmit">
      <div>
        <ModifyForm
          :hiddenBtn='true'
          :editColumn='editColumn'
          :updateData="updateData"
          labelWidth='100px'
          ref="configModal"
          class="ModifyForm"
          :temporaryData='modalData'>
          <div slot="timeTamp">
            <el-date-picker
            v-model="appointmentTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          </div>
        <div slot="timeSlot">
            <el-time-picker
            is-range
            v-model="appointmentTimeSlup"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptionsTime"
            value-format="HH:mm:ss"
            style="height:40px"
          ></el-time-picker>
        </div>
        <div slot="siteBoxSlot">
          <el-checkbox-group v-model="checkList">
            <el-checkbox  v-for="(item,index) in typesList" :key="index" :label="item.id+''">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </div>
        </ModifyForm>
      </div>
    </ModalPanel>
    <!-- 添加编辑end -->
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'coupon:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { dateFormat } from "@/tools/time";
export default {
  name: "couponList1",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    ModifyForm,
    ModalPanel,
  },
  data() {
    return {
      intro:{
        title: '',
        content: `直流桩优惠券，可主动发放给单个用户；或者用户主动领取`
      },
      searchs:{
        component: 'coupon',
        name: '',
        grant: '', 
        type: '',
        state:'',
      },
      tableData: [],
      pager: {
        component: 'coupon',
        use: true,
        total: 0,
        current: 1,
        size: 15,
        showTotal: true
      },
      operation: true,
      //添加编辑
      showUpdate: true,
      appointmentTime: null,
      appointmentTimePost: null,
      appointmentTimeSlup: [],
      pickerOptionsTime: {
          shortcuts: [{
            text: '全天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', ['00:00:00', '23:59:59']);
            }
          }]
        },
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      visible:false,
      modalData:{},
      siteList: [],
      checkList: [],
      typesList:[],
      typeData:[{'id': '1','name': "自营"},{'id':'2', 'name':"第三方"},{'id':'3', 'name':"租用"},{'id':'9', 'name':"私人"}],
      editColumn: [
        // {
        //   name: "优惠券名称",
        //   prop: "name",
        //   type: "text",
        //   width:24,
        //   required: true
        // },
        {
          name: "优惠券类型",
          prop: "type",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择状态"},{'id': 1,'name': "会员折扣"},{'id':2, 'name':"服务费减免"},{'id':3, 'name':"总费用满减"}],
          onChange: (val) => {
            if(val==1){
              this.editColumn[1].hidden = true
            }else{
              this.editColumn[1].hidden = false
            }
          },
          width:24,
          required: true
        },
        {
          name: "使用限制",
          prop: "type1",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': 1,'name': "站点类型"},{'id':2, 'name':"选择站点"}],
          onChange: (val) => {
            this.checkList = []
            if(val==1){
              this.typesList = this.typeData
              this.editColumn[2].hidden = false
              this.editColumn[3].hidden = true
            }else{
              this.typesList = this.siteList
              this.editColumn[2].hidden = true
              this.editColumn[3].hidden = false
            }
          },
          width:24,
          required: false,
          hidden: true,
        },
        {
          name: "可用站点类型",
          prop: "siteTypes",
          type: "other",
          width:24,
          required: false,
          slotName: 'siteBoxSlot',
          hidden: true,
          
        },
        {
        name: "可使用站点",
          prop: "ids",
          type: "other",
          width:24,
          required: false,
          slotName: 'siteBoxSlot',
          hidden: true,
        },
        {
          name: "优惠券金额",
          prop: "amount",
          type: "number",
          width:24,
          required: true
        },
         {
          name: "门槛金额",
          prop: "thresholdAmount",
          type: "number",
          width:24,
          required: true
        },
        //  {
        //   name: "发放数量",
        //   prop: "total",
        //   type: "number",
        //   width:24,
        //   required: true
        // },
        // {
        //   name: "领用时间",
        //   prop: "time",
        //   type: "other",
        //   width:24,
        //   required: false,
        //   slotName: 'timePost',
        //   desc: "活动有效时间"
        // },
        // {
        //   name: "状态",
        //   prop: "state",
        //   type: "select",
        //   optionBindLabel: 'name',
        //   optionBindValue: 'id',
        //   optionList: [{'id': '','name': "请选择状态"},{'id': 1,'name': "未审核"},{'id':2, 'name':"已审核"}],
        //   onChange: () => {},
        //   width:24,
        //   required: true
        // },
        {
          name: "规则说明",
          width: 24,
          prop: "rule",
          type: "text",
          type: "textarea",
          required: false
        },
        // {
        //   name: "发放模式",
        //   prop: "grant",
        //   type: "select",
        //   optionBindLabel: 'name',
        //   optionBindValue: 'id',
        //   optionList: [{'id': '','name': "请选择状态"},{'id': 1,'name': "注册赠送"},{'id':2, 'name':"充值赠送"},{'id':3, 'name':"邀请赠送"},{'id':4, 'name':"会员日送"},{'id':5, 'name':"会员送"},{'id':6, 'name':"场站定向送"},{'id':7, 'name':"平台定向送"},{'id':8, 'name':"积分兑换"},{'id':9, 'name':"扫码活动"}],
        //   onChange: (val) => {
        //     console.log(this.editColumn)
            
        //     var len = this.editColumn.length - 7
        //     if(val==2){
        //       this.editColumn[12].hidden = false
        //       this.editColumn[13].hidden = true
        //       this.editColumn[14].hidden = true
        //     }else if(val == 8){
        //       this.editColumn[12].hidden = true
        //       this.editColumn[13].hidden = false
        //       this.editColumn[14].hidden = true
        //     }else if(val == 9){
        //       this.editColumn[12].hidden = true
        //       this.editColumn[13].hidden = true
        //       this.editColumn[14].hidden = false
        //     }else{
        //       this.editColumn[12].hidden = true
        //       this.editColumn[13].hidden = true
        //       return
        //       console.log(this.editColumn[9].prop)
        //       if(this.editColumn[9].prop ==='chargePrice' || this.editColumn[9].prop ==='score'){
        //         this.editColumn.splice(9,1)
        //       }
        //     }
        //   },
        //   width:24,
        //   required: true
        // },
        // {
        //   name: "充值最低金额",
        //   type: "number",
        //   prop: "chargePrice",
        //   align: "center",
        //   width:24,
        //   required: false,
        //   hidden: true
        // },
        // {
        //   name: "需要积分数",
        //   type: "number",
        //   prop: "score",
        //   align: "center",
        //   width:24,
        //   required: false,
        // },
        // {
        //   name: "单人领取数量",
        //   type: "number",
        //   prop: "number",
        //   align: "center",
        //   width:24,
        //   required: false,
        // },
        {
          name: "有效期方式",
          prop: "way",
          type: "radio",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': 1,'name': "固定时间段"},{'id':2, 'name':"自领取之日开始"}],
          onChange: (val ) => {
            //固定时间段 7
            if(val ==1){
              this.editColumn[9].hidden = false
              // this.editColumn[8].hidden = true
            }else{
              this.editColumn[9].hidden = true
              // this.editColumn[8].hidden = false
            }
          },
          width:24,
          required: true
        },
        // {
        //   name: "时长单位",
        //   prop: "unit",
        //   type: "radio",
        //   optionBindLabel: 'name',
        //   optionBindValue: 'id',
        //   optionList: [{'id': 6,'name': "天"},{'id':2, 'name':"月"}],
        //   onChange: () => {},
        //   width:24,
        //   required: false,
        //   hidden: true
        // },
        {
          name: "有效天数",
          prop: "effectDay",
          type: "number",
          width:24,
          required: false,
          hidden: false,
        },
        {
          name: "开始有效时间",
          prop: "time",
          type: "other",
          width:24,
          required: false,
          hidden: true,
          slotName: 'timeTamp',
          desc: "领取后的使用时间"
        },
        {
          name: "每日可用时段",
          prop: "time",
          type: "other",
          width:24,
          required: false,
          hidden: false,
          slotName: 'timeSlot',
        },
      ],
      //添加编辑end
    };
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center",
            width: '50px'
          },
          {
            label: "类型",
            type: "other",
            prop: "type",
            align: "center",
            width: '120px',
            fnc: val => val == 1 ? "会员折扣" : val == 2 ? "服务费减免" : "总费用减免",
            class: val => val == 1 ? "red-tag" : val == 2 ? "green-tag" : "sheng1"
          },
          {
            label: "面额",
            type: "text",
            prop: "amount",
            align: "center",
            width: '120px'
          },
          {
            label: "使用门槛(元)",
            type: "text",
            prop: "thresholdAmount",
            align: "center"
          },
          
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? "未审核" :"已审核",
            class:  val => val == 1 ? "cancel" :  "agree" ,
          },
          {
            label: "有效期方式",
            type: "other",
            prop: "way",
            align: "center",
            fnc: val => val == 1 ? "固定时间" :"领取时间",
          },
          {
            label: "开始时间",
            type: "text",
            prop: "startTime",
            align: "center"
          },
           {
            label: "有效天数",
            type: "text",
            prop: "effectDay", 
            align: "center"
          },
          {
            label: "使用时间段",
            type: "text",
            prop: "timedun", 
            align: "center",
            width: '170px'
          },
          {
            label: "规则",
            type: "text",
            prop: "rule",
            align: "center",
            overflow: true,
          },
          // {
          //   label: "使用限制",
          //   type: "text",
          //   prop: "siteTypeNames",
          //   align: "center",
          //   overflow: true,
          //   width: '120px'
          // },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  mounted() {
    this.getQueryData();
    this.getStation()
    
  },
  methods: {
    //获取站点
    async getStation(){
      let { data } = await request({ 
      url: "/manage/station/select",
      method: "POST",
      data: {}
      });
      data.map(item => {
        item.name = item.stationName
        return item
      })
      this.siteList= data
    },
    // 审核优惠券
    async checkCoupon(id){
      let res = await request({
          url: `/client/coupon/confirm/${id}`,
          method: 'POST',
        })
        if(res.code !==0) return
        this.$message.success('审核成功')
        this.getQueryData();
    },
  
    async getQueryData() {
      let current =  this.pager.current
      let size = this.pager.size
      let search = objectFilter({ size, current })
      const res = await request({
        url: `/manage/coupon/query`,
        method: "POST",
        data: search
      });
      let data = res.data.records
      data.map(item => {
        if(item.startTimeOfDay){
          item.timedun = item.startTimeOfDay+'至'+item.endTimeOfDay
        }else{
          item.timedun = '全天'
        }
        
        item.priceDesc = `满${item.thresholdAmount}减${item.amount}`
        return item
      })
      this.tableData = data
      this.pager.total = res.data.total
      this.pager.current = res.data.current
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/user/coupon/list",query:{couponId:id,type: "toview"} })
    },
    //添加编辑start
    editStore(rowData,state){
      if(rowData){
        if(rowData.type==1){
          this.editColumn[1].hidden = true
        }else{
          this.editColumn[1].hidden = false
        }
        if (rowData.way){
          var val = rowData.way
          if(val==1){
              //自领取之日开始
              this.editColumn[9].hidden = false
              this.appointmentTime = new Date(rowData.startTime ).getTime()
            }
        }
        if(rowData.stationChannels){
          rowData.type1 = 1
          this.typesList = this.typeData
          var data = rowData.stationChannels.split('|')
          this.checkList = data
          this.editColumn[3].hidden = true
          this.editColumn[2].hidden = false
          // rowData.siteTypes =rowData.siteTypes.split('|')
        }
        if(rowData.stationIds){
          rowData.type1 = 2
          this.typesList = this.siteList
          var data = rowData.stationIds.split('|')
          this.checkList = data
          this.editColumn[3].hidden = false
          this.editColumn[2].hidden = true
          
        }
        this.modalData = {...rowData}
        // this.appointmentTime = [new Date(rowData.couponBeginTime).getTime(), new Date(rowData.couponEndTime).getTime()- 86400000 + 1000]
        this.appointmentTimeSlup = [rowData.startTimeOfDay , rowData.endTimeOfDay ]
      }else{
        // this.appointmentTime = []
        // this.appointmentTimePost = []
        this.modalData ={}
      }
      if(!state || state==1){
        this.showUpdate = true
      }else{
        this.showUpdate = false
      }
      this.visible = true
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    onCancel(){
      this.showSearch = false
      this.visible = false
      this.checkList =[]
    },
    async updateData(values){
      if(this.appointmentTimeSlup.length<1){
        this.$message.error('请选择可使用时段')
        return
      }
      let startTimeOfDay  = this.appointmentTimeSlup[0]
      let endTimeOfDay    = this.appointmentTimeSlup[1]
      // let  couponEndTime= dateFormat(this.appointmentTime ? (this.appointmentTime[1] + 86400000-1000) : undefined, 'yyyy-MM-dd HH:mm:ss')
      // let couponBeginTime = dateFormat(this.appointmentTime ? this.appointmentTime[0] : undefined, 'yyyy-MM-dd HH:mm:ss')
      // let endTime = dateFormat(this.appointmentTimePost ? (this.appointmentTimePost[1] + 86400000-1000) : undefined, 'yyyy-MM-dd HH:mm:ss')
      // let  beginTime = dateFormat(this.appointmentTimePost ? this.appointmentTimePost[0] : undefined, 'yyyy-MM-dd HH:mm:ss')
        // return
       let {id, thresholdAmount, type, rule,  amount, way,effectDay, type1, siteTypes} = values
       let post ={ id, thresholdAmount, startTimeOfDay,endTimeOfDay,effectDay, type, rule, amount,  way}
       var checkList = this.checkList
       var typeData = this.typeData
       var siteList = this.siteList
       console.log('checkList',type1,siteTypes, checkList, typeData,siteList)
      //  1、仅可用于开通会员抵扣
      //  2、同类型优惠券每日仅可用一张
       if(type1==1){
        if(checkList.length <1)return this.$message.error('请选择类型')
        let newdata = typeData.filter(item =>checkList.indexOf(item.id) !=-1).map(item => {return item.name})
        // console.log(newdata)
        var stationChannels  = checkList.join('|')
        var siteTypeNames =newdata.join(',')
        post = {...post, stationChannels}
       }else if(type1==2){
        if(this.checkList.length <1)return this.$message.error('请选择站点')
        let newdata = siteList.filter(item =>checkList.indexOf(item.id+'') !=-1).map(item => {return item.name})
        // console.log(typeData,siteList,newdata)
        var stationIds  = this.checkList.join('|')
        var siteTypeNames =newdata.join(',')
        post = {...post, stationIds  }
       }
      if(post.way==1){
        if(!this.appointmentTime){
          this.$message.error('请选择时间段')
          return
        }
        let startTime = dateFormat(this.appointmentTime ? this.appointmentTime : undefined, 'yyyy-MM-dd HH:mm:ss')
        post = {...post, startTime}
      }
      // if(post.way==2){
      //   post = {...post,  time:values.time}
      // }
      console.log('--------', post)
      let url = id ? "/client/coupon/update": "/client/coupon/add"
      let msg = id ? "编辑成功" : "添加成功"
      let res = await request({
        url: url,
        method: "POST",
        data:post
      })
     if(res.code !==0) return
      this.$message.success(msg)
      this.visible = false
      this.getQueryData();
    },
    //添加编辑end
   
  }
}
</script>
<style lang='scss' >

</style>